package cn.wolfcode.p2p.business.service.impl;

import cn.wolfcode.p2p.Exception.ErrorCode;
import cn.wolfcode.p2p.business.service.ICallInterfaceService;
import cn.wolfcode.p2p.call.util.CallServiceUtil;
import cn.wolfcode.p2p.call.util.Hosting;
import cn.wolfcode.p2p.call.util.SignUtil;
import cn.wolfcode.p2p.call.util.Tools;
import cn.wolfcode.p2p.config.HostingConfig;
import cn.wolfcode.p2p.util.AssertUtil;
import cn.wolfcode.p2p.util.Constant;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class CallInterfaceServiceImpl implements ICallInterfaceService {

    @Autowired
    private HostingConfig hostingConfig;



    @Override
    public void createAccount(String username) {
        //设置基本参数
        Map<String,Object> paramsMap = Hosting.hostingBaseParams(hostingConfig);
        //设置业务参数
        paramsMap = Hosting.hostingServiceParams(paramsMap, username);
        //签名
        String sign = Tools.createLinkString(paramsMap, false, true);
        try {
            sign = SignUtil.sign(sign, hostingConfig.getSignType(), Constant.PRIVATE_KEY, hostingConfig.getInputCharset());
            paramsMap.put("sign",sign);
            //格式化参数
            String linkString = Tools.createLinkString(paramsMap, true, false);
            //调用接口
            String result = CallServiceUtil.sendPost(Constant.URL, linkString);
            //处理结果
            //{"response_code":"APPLY_SUCCESS","partner_id":"200004595271","response_message":"%E6%8F%90%E4%BA%A4%E6%88%90%E5%8A%9F","sign_version":"1.0","_input_charset":"UTF-8","sign":"P9TLvm9Gi8fRdzAlfvQBh5VAhkkJpjUNqTk%2Be43Rwr0cMMPNfO0T8LfUm8IbbpfNkZY1YIstbujWdQebQvNtqhx5oGJeg7I0FDNWNrfrPmac9Cam6f95ibAdrHRC9o3srm76iqI2tMNgSRzQzxHabYAA2AU98W2qffwQdsZT%2F1E%3D","response_time":"20181206075453","sign_type":"RSA"}
            Map<String,String> resultMap = JSON.parseObject(result, Map.class);
            if (resultMap.get("response_code") != null) {
                AssertUtil.instance().isFalse(!SignUtil.Check_sign(resultMap.get("response_message"), resultMap.get("sign"), resultMap.get("sign_type"), Constant.PUBLIC_KEY, hostingConfig.getInputCharset()), ErrorCode.REGISTRATION_FAILED);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
